let db = require('../db/dbmanager');
const crypto = require('crypto');
const { resolve } = require('path');

/**
 * 管理员账号
 */
let Admin={
    checklogin:async(account,password)=>{
        let p =await new Promise(function(resolve,reject){
            let sha256=crypto.createHash('SHA256').update(password).digest('hex');
            let sql   = "SELECT * FROM ADMIN WHERE username=$username and password=$password";
            let param = {$username:account, $password:sha256};
   
            db.sqliteDB.all(sql,param,function(err,row){
                if(err){
                    reject(err);
                }else{
                    resolve(row);
                }
            });
        });
        return p;
    },
    insert:function(account, password){
        let p = new Promise(function(resolve, reject){
            let sql   = "INSERT INTO ADMIN(username,password) VALUES ($username, $password)";
            let sha256= crypto.createHash('SHA256').update(password).digest('hex');
            let param = {$username: account, $password: sha256};
            db.sqliteDB.run(sql, param);
            resolve();
        });
        return p;
    },
    count: function(){
        let p = new Promise(function(resolve,reject){
            let sql = "SELECT COUNT(*) as c FROM ADMIN";
            db.sqliteDB.oneData(sql,(ret)=>{
                resolve(ret.c)
            });
        });
        return p;
    },
    changePass: function(username, old_pass, new_pass){
        // 原密码对不对
        let p = new Promise(function(resolve, reject){
            Admin.checklogin(username, old_pass).then((ret)=>{
                if(ret && ret.length>0){
                    // 更换密码
                    let sql = "UPDATE ADMIN SET password=$password WHERE username=$username";
                    let sha256 = crypto.createHash('SHA256').update(new_pass).digest('hex');
                    let param = {$username: username, $password: sha256};
                    db.sqliteDB.run(sql, param);
                    resolve();
                }
                else{
                    reject('原密码不正确1',username, old_pass);
                }
            }).catch((err)=>{
                console.error('原密码不正确2',err)
                reject(err);
            })
        });
        return p;
    },

};

module.exports = Admin;